package com.copera.cn.kaka;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.copera.cn.kaka.util.ActionUrls;
import com.copera.cn.kaka.util.HttpUtils;
import com.copera.cn.kaka.util.Utility;
import com.copera.cn.kaka.vo.ExchangeRuleVo;
import com.copera.cn.kaka.vo.ShopVo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.mining.app.zxing.camera.CameraManager;
import com.mining.app.zxing.decoding.CaptureActivityHandler1;
import com.mining.app.zxing.decoding.InactivityTimer;
import com.mining.app.zxing.view.ViewfinderView;

/**
 * 扫描二维码
 * 
 * Initial the camera
 * 
 * @author Ryan.Tang
 */
public class MipcaActivityCapture extends BaseActivity implements Callback {

	private ApplicationCustomer appc;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private InactivityTimer inactivityTimer;
	private SurfaceView surfaceView;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private boolean playBeep;
	private boolean vibrate;
	private CaptureActivityHandler1 handler;
	private MediaPlayer mediaPlayer;
	private static final float BEEP_VOLUME = 0.10f;
	private TextView tv_time,tv6,img_01,text_01,text_02,tv_state,tv_code,tv_explain,text_04;
	private RelativeLayout  rl_query;
	private Button set ;
	private String type;
	List<ExchangeRuleVo> list = new ArrayList<ExchangeRuleVo>();
	private RelativeLayout track,exchange,shop;
	private Bitmap logoBitmap;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.barcode);
		tv_state = (TextView) findViewById(R.id.tv_state);//一分钟内是否扫描过
		tv_code = (TextView) findViewById(R.id.tv_code);//上一次扫描的二维码
		CameraManager.init(getApplication());
		type=getIntent().getStringExtra("type");
		
		viewfinderView=(ViewfinderView) findViewById(R.id.viewfinder_view);
		
		appc = (ApplicationCustomer)getAppCustomer();

		hasSurface = false;
		text_01 = (TextView)findViewById(R.id.text_01);
		text_02 = (TextView)findViewById(R.id.text_02);
		surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		inactivityTimer = new InactivityTimer(this);
		tv_time = (TextView)findViewById(R.id.tv_time);
		rl_query = (RelativeLayout)findViewById(R.id.query);
		img_01 = (TextView)findViewById(R.id.img_01);
		track = (RelativeLayout)findViewById(R.id.track);
		exchange = (RelativeLayout)findViewById(R.id.exchange);
		shop = (RelativeLayout)findViewById(R.id.shop);
		tv_explain = (TextView)findViewById(R.id.tv_explain);
		if(type.equals("track")){
			track.setBackgroundResource(R.drawable.check);
			exchange.setBackgroundResource(R.drawable.nocheck);
		}else{
			track.setBackgroundResource(R.drawable.nocheck);
			exchange.setBackgroundResource(R.drawable.check);
		}
		tv_time.setVisibility(View.VISIBLE);
		handlerTime.post(updateThread);
		set = (Button)findViewById(R.id.bt_set);
		tv6 = (TextView)findViewById(R.id.tv6);
		initEvent();
		type = getIntent().getStringExtra("type");
		text_04 = (TextView)findViewById(R.id.text_04);
		if(type.equals("track")){
			tv_time.setVisibility(View.VISIBLE);
			rl_query.setVisibility(View.GONE);
			text_04.setVisibility(View.VISIBLE);
		}else{
			tv_time.setVisibility(View.GONE);
			rl_query.setVisibility(View.VISIBLE);
			text_04.setVisibility(View.GONE);
		}
		appc.getShop().setTrackId(null);
		loadLogomage();
		initValues();
		//强制为竖屏 
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}
	private void initValues(){
		ShopVo shop = appc.getShop();
		text_01.setText(shop.getShopName());
		text_02.setText(shop.getAddress());
	}
	private void initTest(){

		if (appc.getFlag() == null) {
			Intent intent = new Intent();
			appc.setFlag("true");
			intent = new Intent(MipcaActivityCapture.this,TestActivity.class);
			startActivity(intent);
		}
	}
	public void initEvent(){
		set.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(MipcaActivityCapture.this,ShopSetHomeActivity.class);
				recycle();
			    startActivity(intent);
			   
			}
		});
		shop.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(MipcaActivityCapture.this,MainActivity.class);
				recycle();
			    startActivity(intent);
			    finish();
			}
		});
		track.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				handlerTime.postDelayed(updateThread, 1000);
				tv_time.setVisibility(View.VISIBLE);
				rl_query.setVisibility(View.GONE);
				tv_explain.setVisibility(View.GONE);
				text_04.setVisibility(View.VISIBLE);
				track.setBackgroundResource(R.drawable.check);
				exchange.setBackgroundResource(R.drawable.nocheck);
				tv_time.setText("0:59");
				tv_state.setText("0");
				tv_code.setText("0");
				type = "track";
			}
		});
		exchange.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				tv_time.setVisibility(View.GONE);
				rl_query.setVisibility(View.VISIBLE);
				tv_explain.setVisibility(View.GONE);
				text_04.setVisibility(View.GONE);
				track.setBackgroundResource(R.drawable.nocheck);
				exchange.setBackgroundResource(R.drawable.check);
				type = "rule";
				handlerTime.removeCallbacks(updateThread);
			}
		});
		rl_query.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				ShopVo shop = appc.getShop();
				if (shop.getId().equals(shop.getShopId())) {
					Intent intent = new Intent(MipcaActivityCapture.this,CardExchangeActivity.class);
					recycle();
					startActivity(intent);
					 finish();
				}else{
					Toast.makeText(MipcaActivityCapture.this, "只有店主才能修改兑换规则",Toast.LENGTH_SHORT).show();
				}
			}
		});
		
	}
	
	//清楚Bitmap图片缓存
	private void recycle(){
		if (logoBitmap != null) {
			logoBitmap.recycle();
		}
	}
	
	//计时器
	Handler handlerTime = new Handler();
	Runnable updateThread = new Runnable() {
		@Override
		public void run() {
			handlerTime.postDelayed(updateThread, 1000);
			String str = tv_time.getText().toString();
			int num = Integer.parseInt(str.substring(2, 4));
			if(num > 0){
				num = num - 1;
				if (num > 9) {
					tv_time.setText("0:"+num);
				}else {
					tv_time.setText("0:0"+num);
				}
			}else{
				tv_time.setText("0:59");
				if ("1".equals(tv_state.getText()) && appc.getShop().getTrackId() != null) {
					tv_state.setText("0");
					tv_code.setText("0");
					tv_time.setText("01:00");
					tv_explain.setVisibility(View.VISIBLE);
					handlerTime.removeCallbacks(updateThread);
				}else {
					tv_state.setText("0");
					tv_code.setText("0");
				}
			}
		}
	};
	@Override
	public void onResume() {
		if (appc.getShop().getTrackId() != null) {
			handlerTime.postDelayed(updateThread, 1000);
		}else {
			if ("true".equals(appc.getShop().getIfTime())) {
				handlerTime.postDelayed(updateThread, 1000);
			}
		}
		initTest();
		tv_time = (TextView)findViewById(R.id.tv_time);
        loadData();
        loadLogomage();
		super.onResume();
       
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) 
				getSystemService(Context.AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
		
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	private String barCode;
	private String sid;

	private void loadData() {
		new AsyncTask<String, Integer, JSONObject>() {

			@Override
			protected JSONObject doInBackground(String... params) {
				JSONObject jsonObj = null;
				try {
					String jsonStr = HttpUtils.get(params[0], getAppCustomer()
							.getHttpClient());

					if (jsonStr != null) {
						jsonObj = new JSONObject(jsonStr);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return jsonObj;
			}

			@Override
			protected void onPostExecute(JSONObject jo) {

				if (jo != null) {
					try {
						if(jo.getString("size")!=null){
							tv6.setText(jo.getString("size")+"/");
						}

					} catch (Exception e) {
						e.printStackTrace();
						if (e.getMessage() != null) {

						}
					}
				}
			}

		}.execute(ActionUrls.URL_EXCHANGERULE_LIST+"?shopId="+getValue("shopId"));
		
	}

	/**
	 * 处理扫描结果
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		
		barCode = result.getText();
		if (barcode != null && !"".equals(barcode)) {
			if(type.equals("track")){
				if(barCode.indexOf("kaka")==-1){
					Toast.makeText(MipcaActivityCapture.this, "非法二维码，请确认记录足迹的二维码是否正确", Toast.LENGTH_LONG).show();
					
					Intent intent = new Intent(this,MipcaActivityCapture.class);
					Bundle bundle = new Bundle();
					bundle.putString("type", "track");
					intent.putExtras(bundle);
				    startActivity(intent);
				    finish();
				}else{
					String url = ActionUrls.URL_TRACK_SAVE+"?nickName="+barCode.replace("kaka", "")+"&shopId="+getValue("shopId");
				    Intent intent = new Intent(MipcaActivityCapture.this,TrackRecordActivity.class);
					if ("0".equals(tv_state.getText())) {
						tv_state.setText("1");
						tv_code.setText(barCode);
						tv_code.setVisibility(View.GONE);
						intent.putExtra("state", "0");
						tv_time.setText("0:60");
					}else {
						
						if(tv_code.getText().equals(barCode)){
							intent.putExtra("state", "1");
						}else {
							intent.putExtra("state", "0");
							tv_time.setText("0:60");
							tv_code.setText(barCode);
						}
						tv_code.setVisibility(View.GONE);
					}
					tv_explain.setVisibility(View.GONE);
					handlerTime.removeCallbacks(updateThread);
					intent.putExtra("url", url);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					recycle();
					startActivity(intent);
				}
				
			}else{
				if(barCode.indexOf("ruleId")==-1){
					Toast.makeText(MipcaActivityCapture.this, "非法二维码，请确认兑换的二维码是否正确", Toast.LENGTH_LONG).show();
					
					Intent intent = new Intent(this,MipcaActivityCapture.class);
					Bundle bundle = new Bundle();
					bundle.putString("type", "rule");
					intent.putExtras(bundle);
				    startActivity(intent);
				    finish();
				}else{
					String shopId = barCode.substring(barCode.indexOf("shopId=")+7, barCode.length());
					if (appc.getShop().getShopId().equals(shopId)) {
						String url = ActionUrls.URL_EXCHANGERECORD_CONFIRM+barCode;
						Intent intent = new Intent(this,ExchangeConfirmActivity.class);
						intent.putExtra("url", url);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						
						startActivity(intent);
					}else {
						Toast.makeText(MipcaActivityCapture.this, "非法二维码，请确认是否是在本店铺申请的兑换", Toast.LENGTH_LONG).show();
						
						Intent intent = new Intent(this,MipcaActivityCapture.class);
						Bundle bundle = new Bundle();
						bundle.putString("type", "rule");
						intent.putExtras(bundle);
					    startActivity(intent);
					    finish();
					}
				}
				
			}
			
		}

	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler1(this, decodeFormats,
					characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
		
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};
	 /**监听对话框里面的button点击事件*/  
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()  
    {  
        public void onClick(DialogInterface dialog, int which)  
        {  
            switch (which)  
            {  
            case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序  
            	appExit();
                break;  
            case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框  
                break;  
            default:  
                break;  
            }  
        }  
    };
    @SuppressWarnings("deprecation")
	@Override  
    public boolean onKeyDown(int keyCode, KeyEvent event)  
    {  
        if (keyCode == KeyEvent.KEYCODE_BACK )  
        {  
            // 创建退出对话框  
            AlertDialog isExit = new AlertDialog.Builder(this).create();  
            // 设置对话框标题  
            isExit.setTitle("系统提示");  
            // 设置对话框消息  
            isExit.setMessage("确定要退出吗");  
            // 添加选择按钮并注册监听  
            isExit.setButton2("取消", listener);  
            isExit.setButton("确定", listener);  
           
            // 显示对话框  
            isExit.show();  
  
        }  
          
        return false;  
          
    }  
	
	//加载logo图片
  	private void loadLogomage() {
  		new AsyncTask<String, Integer, BitmapDrawable>() {
  			@SuppressWarnings("deprecation")
			@Override
  			protected  BitmapDrawable doInBackground(String... params) {
  				BitmapDrawable bd;
  				try {
  					logoBitmap = getPic(ActionUrls.HOST_IMG+getValue("headImage"));
  					if(logoBitmap != null){
  						bd=new BitmapDrawable(logoBitmap); 
  						if (logoBitmap != null && !logoBitmap.isRecycled()) 
  	  					{ 
  							logoBitmap=null;
  	  					} 
  	  					return bd;
  					}
  					
  				} catch (Exception e) {
  					e.printStackTrace();
  				}
  				return null;
  			}
  			protected void onPostExecute(BitmapDrawable bd) {
  				if (bd != null) {
  					img_01.setBackgroundDrawable(bd);
				}
			}

  		}.execute("");
  	}
  	
  	public Bitmap getPic(String uriPic) {
	    URL imageUrl = null;
	    Bitmap bitmap = null;
	    try {
	        imageUrl = new URL(uriPic);
	    } catch (MalformedURLException e) {
	        e.printStackTrace();
	    }
	    try {
	        HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
	        conn.connect();
	        int nRC = conn.getResponseCode();//得到连接状态
	        if(nRC == HttpURLConnection.HTTP_OK){
	        	InputStream is = conn.getInputStream();
		        bitmap = BitmapFactory.decodeStream(is);
		 
		        is.close();
	        }
	 
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return bitmap;
	}
}
